package com.chenziwen.scala.chapter08

object Scala12_FoldFunction {
  def main(args: Array[String]): Unit = {
    // 折叠
    val list = List(1, 2, 3, 4)

    def minus(num1: Int, num2: Int): Int = {
      num1 - num2
    }
    // 效果：((((5-1)-2)-3)-4) = -5
    println(list.foldLeft(5)(minus))
    println((5 /: list) (minus))
    // 效果：(1 -(2 -(3 - (4-5))) = 3
    println(list.foldRight(5)(minus))
    println((list :\ 5) (minus))

    // 注：foldLeft和foldRight有一种缩写方法对应分别是【/:】【:\】

    val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD,R"
    // 统计上面字符串中每个字符出现的次数

    def charCount(map: Map[Char, Int], c: Char): Map[Char, Int] = {
      map + (c -> (map.getOrElse(c, 0) + 1))
    }

    println(sentence.foldLeft(Map[Char, Int]())(charCount))
  }
}
